package com.example.util;

import com.example.pojo.CollarMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author w
 */
@Component
public class RedisUtil {
    private static RedisTemplate<String,Object> redisTemplate;

    @Autowired
    public void init(RedisTemplate<String,Object> redisTemplate) {
        RedisUtil.redisTemplate= redisTemplate;
    }

    public static void setSleepTime(String ip,int sleepTime){
        HashOperations<String, Object, Object> opsForHash = redisTemplate.opsForHash();
        if (!opsForHash.hasKey(ip,"sleepTime")) {
            opsForHash.put(ip,"sleepTime",sleepTime);
        }
    }

    public static int getSleepTime(String ip){
        HashOperations<String, Object, Object> opsForHash = redisTemplate.opsForHash();
        Object sleepTime = opsForHash.get(ip, "sleepTime");
        if (sleepTime==null){
            sleepTime = -1;
        }
        return (int) sleepTime;
    }

    public static void setRecentMsg(String ip, CollarMsg collarMsg){
        HashOperations<String, Object, Object> opsForHash = redisTemplate.opsForHash();
        opsForHash.put(ip,"recentMsg",collarMsg);
    }

    public static CollarMsg getRecentMsg(String ip){
        HashOperations<String, Object, Object> opsForHash = redisTemplate.opsForHash();
        Object recentMsg = opsForHash.get(ip, "recentMsg");
        if (recentMsg==null){
            return null;
        }else {
            return (CollarMsg) recentMsg;
        }
    }

    public static void putCollarMsg(String ip,CollarMsg collarMsg){
        HashOperations<String, Object, Object> opsForHash = redisTemplate.opsForHash();
        if (!opsForHash.hasKey(ip, "historyMsg")) {
            List<CollarMsg> list = new ArrayList<>();
            list.add(collarMsg);
            opsForHash.put(ip, "historyMsg",list);
        }else {
            List<CollarMsg> historyMsg = (List<CollarMsg>) opsForHash.get(ip, "historyMsg");
            assert historyMsg != null;
            historyMsg.add(collarMsg);
            opsForHash.put(ip, "historyMsg",historyMsg);
        }
    }

    public static List<CollarMsg> getHistoryMsgs(String ip){
        HashOperations<String, Object, Object> opsForHash = redisTemplate.opsForHash();
        Object historyMsg = opsForHash.get(ip, "historyMsg");
        if (historyMsg==null){
            return new ArrayList<>();
        }else {
            return (List<CollarMsg>) historyMsg;
        }
    }
}
